package com.github.cyf.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author chenyifan
 * @create 2024-11-14 17:21
 */
@Configuration
@EnableAsync // 使用异步方法时需要提前开启(在启动类上或配置类上)
@EnableScheduling
public class ThreadPoolConfig {

    private static final int corePoolSize = 5;
    private static final int maxPoolSize = 20;
    private static final int keepAliveTime = 100;
    private static final int queueCapacity = 200;
    private static final String threadNamePrefix = "async-exec-";

    /**
     * 自定义线程池
     * @return
     */
    @Bean("threadPoolTaskExecutor")
    public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 核心线程池大小
        executor.setCorePoolSize(corePoolSize);
        // 最大可创建的线程数
        executor.setMaxPoolSize(maxPoolSize);
        // 等待队列最大长度
        executor.setQueueCapacity(queueCapacity);
        // 线程池维护线程所允许的空闲时间
        executor.setKeepAliveSeconds(keepAliveTime);
        // 线程池对拒绝任务(无线程可用)的处理策略
        // 当线程池和队列已满，新提交的任务将由调用者所在的线程执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 线程名前缀
        executor.setThreadNamePrefix(threadNamePrefix);
        // 初始化
        executor.initialize();
        return executor;
    }

    /**
     * 执行周期性或定时任务
     * @return
     */
    @Bean("threadPoolTaskScheduler")
    public ThreadPoolTaskScheduler threadPoolTaskScheduler(){
        ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
        // 线程池大小
        threadPoolTaskScheduler.setPoolSize(corePoolSize);
        // 线程名称前缀
        threadPoolTaskScheduler.setThreadNamePrefix("schedule-exec-");
        // 等待时长
        threadPoolTaskScheduler.setAwaitTerminationSeconds(60);
        // 调度器shutdown被调用时等待当前被调度的任务完成
        threadPoolTaskScheduler.setWaitForTasksToCompleteOnShutdown(true);
        return threadPoolTaskScheduler;
    }
}